<template>
  <div class="cart">
    <van-nav-bar title="购物车" />
    <ul>
      <li v-for="(item,index) in cartList" :key="index">
         <input type="checkbox" v-model="item.check" @change="check">
         <img :src="item.img" alt="">
         <section>
           <h5>{{item.name}}</h5>
           <p>
             <span>￥{{item.price}}</span>
             <van-stepper v-model="item.buyNum" />
           </p>
         </section>
      </li>
    </ul>
    <div class="foot">
      <span class="left"><input type="checkbox" v-model="checkAll" @change="$store.commit('checkAll',checkAll)">&nbsp;全选</span>
      <span>合计：<b style="color:red">￥{{all.price}}</b></span>
      <span class="right">结算（{{all.num}}）</span>
    </div>
  </div>
</template>

<script>
import { ref, reactive, toRefs, computed } from "vue";
import { useStore } from 'vuex';
export default {
  setup() {
    const { state } = useStore();
    const data = reactive({
      cartList: computed(() => state.cart),
      checkAll: state.cart.every(item => item.check),
      all: computed(() => {
        let num = 0,price = 0;
        state.cart.forEach(item => {
          if(item.check){
            num+=item.buyNum
            price+=item.buyNum*item.price
          }
        })
        return {num:num,price:price}
      })
    })
    const check = () => {
      data.checkAll = data.cartList.every(item => item.check);
    }
    return{
      ...toRefs(data),
      check
    }
  },
};
</script>
<style lang="scss" scoped>
ul{
  height: calc(100% - 96px);
  overflow: auto;
  li{
    display: flex;
    padding: 10px;
    box-sizing: border-box;
    align-items: center;
    img{
      width: 60px;
      margin: 0 10px;
    }
    section{
      flex: 1;
      span{
        color: red;
      }
      .van-stepper{
        float: right;
      }
    }
  }
}
.foot{
  display: flex;
  height: 50px;
  align-items: center;
  justify-content: space-between;
  border-top: 1px solid #ccc;
  .left{
    margin-left: 10px;
  }
  .right{
    background: red;
    color: #fff;
    line-height: 50px;
    padding: 0 5px;
  }
}
</style>